<?php

namespace App\Http\Controllers\Logic;

use App\Http\Controllers\Controller;
use App\Model\OACity;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

/**
 * Class CityLogic
 * @package App\Http\Controllers\Logic
 * @desc 城市相关操作
 */

class CityLogic extends Controller
{
    //城市列表
    public function getCityList($params)
    {
        try {
            $query = OACity::query();
            //等级
            if(isset($params['level']) && !empty($params['level'])) $query->where('level',$params['level']);
            //创建时间
            if(isset($params['created_start']) && !empty($params['created_start']) && isset($params['created_end']) && !empty($params['created_end'])){
                $query->whereBetween('created_at',[$params['created_start'],$params['created_end']]);
            }
            //金额
            if(isset($params['money_min']) && !empty($params['money_min'])) $query->where('money','>=',$params['money_min']);

            if(isset($params['money_max']) && !empty($params['money_max'])) $query->where('money','<=',$params['money_max']);

            $list = $query->orderBy('updated_at','DESC')->paginate($params['page_size'],['*']);

            $city_level_list = OACity::query()->groupBy('level')->get(['level'])->toArray();
            //dd($city_level_list);
            $city_zh = ['','一','二','三','四','五','六','七','八','九','十'];
            foreach ($city_level_list as &$val){
                $val['label'] = $city_zh[$val['level']] . '线城市';
            }
            //dd($city_level_list);
            $list = $list->toArray();
            //dd($list);
            $list['city_list'] = $city_level_list;
            if(empty($list['data'])) return $list;

            foreach ($list['data'] as &$item){
                $item['city'] = $city_zh[$item['level']] . '线城市';
            }
            //dd($list);
            return $list;

        }catch (\Exception $e){
            ret_json('err',$e->getMessage());
        }
    }

    //编辑城市
    public function editCity($params): bool
    {
        try{
            DB::beginTransaction();
            $city = OACity::query()->where('id',$params['id'])->first();
            if(!is_null($city)){
                $city->money = $params['money'];
                $city->level = $params['level'];
                $city->save();
            }else{
                $params['created_at'] = $params['updated_at'] = date('Y-m-d H:i:s');
                unset($params['id']);
                OACity::query()->insertGetId($params);
            }
            DB::commit();
            return true;
        }catch (\Exception $e){
            DB::rollBack();
            throw new \Exception($e->getMessage());
        }
    }
}
